package com.example.c_reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test02 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<Person> personClass = Person.class;
        Constructor<Person> constructor = null;
        try {
            constructor = personClass.getConstructor(String.class, int.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        System.out.println("constructor:" + constructor);

        Person person = null;
        try {
            person = constructor.newInstance("sansha", 29);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        System.out.println("person:" + person);

        System.out.println("========获取所有的constructors==========");
        Constructor<?>[] declaredConstructors = personClass.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println("declaredConstructor:" + declaredConstructor);
        }

        System.out.println("========获取指定的constructors==========");
        Constructor<Person> declaredConstructor = personClass.getDeclaredConstructor(String.class);
//        操作私有的constructor时，先使用父类Accessible，进行设置
        declaredConstructor.setAccessible(true);  // 进行暴力反射
        Person person1 = declaredConstructor.newInstance("c十秒");
        System.out.println(person1);
    }
}
